import { ElIcon, ElImage, ElUpload } from "element-plus";
import { Image, Uploader, showImagePreview } from "vant";
import { Plus } from "@element-plus/icons-vue";
import { Form } from "../model/base/form";
import { GroupForm } from "../model/base/group";
import { GroupList } from "@b/model/base/group";
import { h } from "vue";
import { adminStore } from "../store/index";
import defaultAvatar from "../src/assets/OIP-C.jpg?url";
import type { RuleItem } from "async-validator";
import { Http } from "@b/model/base/http";

export class UserSign extends Http {
    showSet: boolean = false
    showSign: boolean = false
    showCode: boolean = false
    showCheck: boolean = false
    checkCoded: string = ''
    code: string = ''
    sign: string = ''
    signToken: string = ''
    min2: number = 1000

    constructor() {
        super()
        this.watch('showSign', (newVal) => {
            if (!newVal) {
                this.sign = ''
            }
        })
    }

    async checkTimeOut() {
        const res = await this.request('/user/checkSign', { data: { signToken: this.signToken } })
        if (res) {
            return true
        } else {
            this.showCheck = true
            return false
        }
    }

    async checkCode() {
        this.signToken = await this.request('/user/checkCode', { data: { code: this.checkCoded } })
        this.checkCoded = ''
        this.showCheck = false
    }

    async setCode() {
        if (!await this.checkTimeOut()) return
        const { code, signToken } = this
        const res = await this.request('/user/setCode', { data: { code, signToken } })
        if (res) {
            this.code = ''
            this.showCode = false
        }
    }

    async getSign() {
        this.showSign = true
        if (!await this.checkTimeOut()) return
        this.sign = await this.request('/user/getSign', { data: { signToken: this.signToken } })
    }

    async setSign(sign: string) {
        if (!await this.checkTimeOut()) return
        const url = await this.imgUpload(sign)
        const res = await this.request('/user/setSign', { data: { sign: url, signToken: this.signToken } })
        if (res) {
            this.showSet = false
            this.showConfirm('设置成功，是否更新签名密码？').then(() => {
                this.showCode = true
            })
        }
    }
}

export class UserSelfForm extends Form<interfaceUser> {
    pages: { value: string | number, text: string }[]
    constructor() {
        super()
        this.title = "用户详情"
        this.pages = []
        this.upload = ["headImg"]
        this.url.update = "/user/update/self"
        this.url.info = "/user/userinfo"
        this.label_width = '5em'
    }
    setLabels() {
        const vName: RuleItem[] = [{
            type: 'string', required: true, validator: (rule, value) => value && value.length <= 16 && value.length >= 2,
            message: '长度在2-16之间'
        }]
        const vPhone: RuleItem[] = [{
            type: 'string', required: true, validator: (rule, value) => value && value.length == 11,
            message: '手机号长度为11位'
        }]
        this.rule = {
            name: vName,
            phone: vPhone
        }
        this.setItem({
            name: {
                prop: 'name',
                label: '姓名',
                type: 'text',
                required: true,
                rule: Form.getVantRule(vName)
            },
            username: {
                prop: 'username',
                label: '账号',
                type: 'text',
                required: true,
                show: ({ type }) => type !== 'form',
            },
            phone: {
                prop: 'phone',
                label: '手机号',
                type: 'text',
                required: true,
                rule: Form.getVantRule(vPhone)
            },
            roles: {
                prop: 'roles',
                label: '权限',
                type: 'customize',
                vform: () => h('div'),
                formatter: ({ value }) => {
                    return value?.map((item) => item.name).join(',')
                },
                show: ({ type }) => type !== 'form'
            },
            remark: {
                prop: 'remark',
                label: '擅长',
                type: 'textarea',
                required: true,
            },
            headImg: {
                prop: 'headImg',
                label: '头像',
                type: 'customize',
                formatter: ({ value }) => h(ElImage, {
                    src: value || defaultAvatar, alt: '头像', style: { height: '120px', width: '120px' }
                }),
                p_formatter: ({ value }) => h(Image, {
                    src: value, alt: '头像', style: { width: '80px', height: '80px' }, onClick: () => {
                        if (value) showImagePreview([value])
                    }
                }),
                vform: ({ value }) => {
                    return h('div', {}, h(ElUpload, {
                        class: 'avatar',
                        autoUpload: false, showFileList: false, accept: 'image/*', onChange: async (file) => {
                            if (!file.raw) return
                            this.showCroppe(URL.createObjectURL(file.raw))
                        }
                    }, { default: () => value ? h(ElImage, { src: value }) : h(ElIcon, {}, { default: () => h(Plus) }) }))
                },
                p_vform: ({ prop, data, value }) => {
                    return h(Uploader, {
                        afterRead: (file) => {
                            if (Array.isArray(file)) {
                                if (file.length > 0) {
                                    file = file[0]
                                } else {
                                    return
                                }
                            }
                            if (file.file) this.showCroppe(URL.createObjectURL(file.file))
                        },
                        onDelete: () => {
                            data[prop] = ''
                        },
                        previewFullImage: false,
                        maxCount: 1,
                        modelValue: value ? [{ url: value, isImage: true }] : undefined
                    })
                }
            }
        }, this.labels)
    }

    init() {
        this.setLabels()
    }
    async getPages() {
        const pages = await this.request('/v1/user/menus_page')
        this.pages = pages.map((item: { label: string; url: string; }) => ({ text: item.label, value: item.url }))
    }
    async setPageIndex(url: string) {
        await this.request('/v1/user/setPageIndex', { data: { url } })
    }
    showCroppe(url: string) {
        console.log(url)
        throw new Error('未设置显示编辑图片的方法')
    }
    async afterUpdateData() {
        await adminStore().setuserInfo('recache')
        this.id = 1
        this.setData()
        this.show = true
    }
}
export class ResetPassword extends Form<interfacePassword> {
    constructor() {
        super()
        this.url.add = "/token/change_password"
        this.label_width = "6em"
    }
    setLabels() {
        const vPassword: RuleItem[] = [{
            type: 'string', required: true, validator: (rule, value) => value ? value.length < 32 && value.length >= 5 : false,
            message: '密码位数在6-32之间'
        }]
        this.rule = {
            oldPassword: vPassword,
            newPassword1: vPassword,
            newPassword2: vPassword
        }
        this.setItem({
            oldPassword: {
                label: '原密码',
                prop: 'oldPassword',
                required: true,
                type: "password",
                rule: Form.getVantRule(vPassword)
            },
            newPassword1: {
                label: '新密码',
                prop: 'newPassword1',
                required: true,
                type: "password",
                rule: Form.getVantRule(vPassword)
            },
            newPassword2: {
                label: '确认密码',
                prop: 'newPassword2',
                required: true,
                type: "password",
                rule: Form.getVantRule(vPassword)
            }
        }, this.labels)
    }
    init() {
        this.setLabels()
    }
    afterUpdateData() {
        adminStore().logOut()
    }
}
export class AccountGroupList extends GroupList {
    constructor() {
        super()
        this.title = "会话"
        this.url.page = "/vv/group/groupList"
    }
}
export class notReadGroupList extends GroupList {
    constructor() {
        super()
        this.title = ""
        this.url.page = "/vv/group/notReadgroupList?key=1"
        this.immediateCheck = false
    }
}
export class C2CGroupForm extends GroupForm {
    storeId: string
    constructor() {
        super()
        this.title = '会话'
        this.message = ''
        this.type = 'text'
        this.newMessage = 0
        this.storeId = ''
        this.url.page = "/vv/group/history"
        this.url.delete = "/vv/group/back"
    }
}